
import { _decorator, Node, MeshRenderer, Prefab, Texture2D, v3, Layers, Material, renderer, SkinnedMeshRenderer, Vec4, UIMeshRenderer } from 'cc';
import GameData from '../../Script/Common/GameData';
import GlobalPool, { customPoolScript } from '../../Script/Common/GlobalPool';
import Loader from '../../Script/Common/Loader';
import PlayerData from '../../Script/Common/PlayerData';
import yyComponent from '../../Script/Common/yyComponent';
import { EventType } from '../../Script/GameSpecial/GameEventType';
import { GlobalEnum } from '../../Script/GameSpecial/GlobalEnum';
const { ccclass, property } = _decorator;

@ccclass('ShopRole')
export class ShopRole extends yyComponent {

    public init() {
        this.initSub();
        this.onEvents();
        this.updateState();
    }

    protected initSub() {
        this.initHat();
        this.initSkin();
        this.initWeapon();
    }
    protected resetSub() {
        this.resetSkin();
        // this.resetHat();
        // this.resetWeapon();
    }
    protected onEvents() {
        this.on(EventType.LevelEvent.setPreview, this.setPreview, this);
        this.on(EventType.Common.UIEvent.exited, this.onExitUI, this);
    }
    public reuse() {
        this.reset();
        this.onEvents();
        console.log("shoprole又注册了事件");
        this.updateState();
    }
    public unuse() {
        this.reset();
        this.offEvents();
        console.log("shoprole注销事件");
    }
    public updateState() {
        let skin = PlayerData.getData("gameData.PlayerSkin.cur");
        this.setSkin(skin);
        let weapon = PlayerData.getData("gameData.WeaponSkin.cur");
        this.setWeapon(weapon.type, weapon.id);
        let hat = PlayerData.getData("gameData.HatSkin.cur");
        this.setHat(hat);
    }

    /***********************************************对外方法***********************************************/
    public setSkin(id = 0) {
        if (this.skinId === id) return;
        //加载对应贴图赋值给材质球
        this.skinId = id;
        Loader.loadBundleRes("Role", "PlayerSkin2/skin" + this.skinId, (res) => {
            let t = new Texture2D();
            t.image = res;
            this.mat.setProperty("mainTexture", t);
        });
    }
    public removeSkin() {
        this.setSkin(0);
    }
    /**
     * 设置角色使用的武器
     * @param type 武器类型
     * @param id 该类型下的武器id
     */
    public setWeapon(type?: GlobalEnum.WeaponType, id?: number) {
        if (undefined === type) {
            type = GlobalEnum.WeaponType.katana;
            id = 1;
        }
        if (this.weaponType === type && this.weaponId === id) {
            return;
        }
        this.removeWeapon();
        this.weaponType = type;
        this.weaponId = id;
        if (this.weaponType == GlobalEnum.WeaponType.none) {
            return;
        }
        //加载武器模型
        let str = this.weaponType + this.weaponId;
        if (this.weaponType == GlobalEnum.WeaponType.trapper) {
            str += "player";
        }
        let node = GlobalPool.get(str);
        if (!!node) {
            this.addWeapon(node);
        } else {
            Loader.loadBundle("Weapon", () => {
                Loader.loadBundleRes("Weapon", "Prefab/" + str, (res) => {
                    GlobalPool.createPool(str, res, str);
                    let node = GlobalPool.get(str);
                    this.addWeapon(node);
                });
            }, false, false);
        }
    }
    /**移除武器节点 */
    public removeWeapon() {
        for (let i = this.leftHand.children.length - 1; i >= 0; --i) {
            this.removeFromUI(this.leftHand.children[i]);
        }
        for (let i = this.rightHand.children.length - 1; i >= 0; --i) {
            this.removeFromUI(this.rightHand.children[i]);
        }
        GlobalPool.putAllChildren(this.leftHand);
        GlobalPool.putAllChildren(this.rightHand);
        this.weaponType = GlobalEnum.WeaponType.none;
        this.weaponId = 0;
    }
    /**设置饰品 */
    public setHat(id: number = 0) {
        if (this.hatId === id) return;
        this.resetHat();
        this.hatId = id;
        if (id == 0) {
            return;
        }
        let node = GlobalPool.get("hat" + id);
        if (!!node) {
            this.addToUI(node);
            this.hatLayer.addChild(node);
        } else {
            Loader.loadBundle("Hat", () => {
                Loader.loadBundleRes("Hat", "Prefab/hat" + id, (res) => {
                    GlobalPool.createPool("hat" + id, res, null);
                    Loader.loadBundleRes("Hat", "Textures/hat" + id, (res) => {
                        let hat = GlobalPool.get("hat" + id);
                        this.addToUI(hat);
                        this.hatLayer.addChild(hat);
                        let mat = hat.getComponent(MeshRenderer).getMaterialInstance(0);
                        let t = new Texture2D();
                        t.image = res;
                        mat.setProperty("mainTexture", t);
                    });
                }, Prefab, false);
            }, false, false);
        }
    }
    /**移除饰品 */
    public removeHat() {
        for (let i = this.hatLayer.children.length - 1; i >= 0; --i) {
            this.removeFromUI(this.hatLayer.children[i]);
        }
        GlobalPool.putAllChildren(this.hatLayer);
        this.hatId = null;
    }

    protected addToUI(node: Node) {
        node.layer = Layers.Enum.UI_2D;
        node.addComponent(UIMeshRenderer);
    }
    protected removeFromUI(node: Node) {
        node.layer = Layers.Enum.DEFAULT;
        node.removeComponent(UIMeshRenderer);
    }

    //#region 人物模型
    @property(SkinnedMeshRenderer)
    protected skin: SkinnedMeshRenderer = null;
    protected mat: Material = null;
    public skinId: number = null;
    protected initSkin() {
        if (!this.skin) {
            this.skin = this.node.getComponentInChildren(SkinnedMeshRenderer);
        }
        this.mat = this.skin.getMaterialInstance(0);
    }
    protected resetSkin() {
    }
    //#endregion

    //#region 武器
    /**左手节点（武器要挂载的节点） */
    @property(Node)
    protected leftHand: Node = null;
    /**右手节点 */
    @property(Node)
    protected rightHand: Node = null;
    /**当前使用的武器类型 */
    public weaponType: GlobalEnum.WeaponType = GlobalEnum.WeaponType.none;
    /**当前使用的武器在该类型下的id，0表示没有使用武器 */
    protected weaponId: number = 0;
    protected initWeapon() {
    }
    protected resetWeapon() {
        this.removeWeapon();
    }

    /**添加武器节点 */
    protected addWeapon(node: Node) {
        switch (this.weaponType) {
            // case GlobalEnum.WeaponType.claw: {
            //     this.addToUI(node);
            //     this.leftHand.addChild(node);
            //     node.setPosition(0.003, 0.003, 0.005);
            //     node.eulerAngles = v3(9.877, -259.844, 231.35);
            //     let node2 = GlobalPool.get(this.weaponType + this.weaponId);
            //     this.addToUI(node2);
            //     this.rightHand.addChild(node2);
            //     node2.setPosition(-0.005, 0.002, 0.005);
            //     node2.eulerAngles = v3(34.532, -114.508, 107.723);
            //     break;
            // }
            case GlobalEnum.WeaponType.trapper: {
                this.addToUI(node);
                let s = 1;
                node.setScale(s, s, s);
                node.setPosition(0, 0, -0.007);
                node.eulerAngles = v3();
                this.rightHand.addChild(node);
                node[customPoolScript].offEvents();
                break;
            }
            default: {
                this.addToUI(node);
                this.rightHand.addChild(node);
                break;
            }
        }
    }

    //#endregion

    //#region 饰品
    @property(Node)
    protected hatLayer: Node = null;
    protected hatId: number = null;
    protected initHat() { }
    protected resetHat() {
        this.removeHat();
    }

    //#endregion

    protected setPreview(data: { type: string, data: { id: number, type: string } }) {
        switch (data.type) {
            case "skin": {
                this.setSkin(data.data.id);
                break;
            }
            case "hat": {
                this.setHat(data.data.id);
                break;
            }
            default: {
                this.setWeapon(data.data.type, data.data.id);
                break;
            }
        }
    }

    protected onExitUI(ui) {
        if (ui == GlobalEnum.UI.shop) {
            this.updateState();
        }
    }

}
